package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.AlbumMediaRequest;
import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.entity.AlbumMedia;
import com.ruoyi.livedemo.mapper.AlbumMediaMapper;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class AlbumService {

    private final AlbumMediaMapper albumMediaMapper;

    public PagedResult<AlbumMedia> list(Long userId, int page, int size) {
        int pageSize = size <= 0 ? 12 : size;
        int currentPage = Math.max(page, 0);
        int offset = currentPage * pageSize;
        List<AlbumMedia> items = albumMediaMapper.findPage(userId, offset, pageSize);
        long total = albumMediaMapper.countByUser(userId);
        return new PagedResult<>(total, items);
    }

    @Transactional
    public AlbumMedia create(Long userId, AlbumMediaRequest request) {
        AlbumMedia media = new AlbumMedia();
        media.setUserId(userId);
        media.setTitle(request.getTitle());
        media.setDescription(request.getDescription());
        media.setMediaType(request.getMediaType());
        media.setFilePath(request.getFilePath());
        media.setTakenAt(request.getTakenAt());
        media.setMood(request.getMood());
        albumMediaMapper.insert(media);
        return media;
    }

    @Transactional
    public AlbumMedia update(Long userId, Long id, AlbumMediaRequest request) {
        AlbumMedia media = albumMediaMapper.findByIdAndUser(id, userId);
        if (media == null) {
            throw new IllegalArgumentException("未找到对应的相册记录");
        }
        media.setTitle(request.getTitle());
        media.setDescription(request.getDescription());
        media.setMediaType(request.getMediaType());
        media.setFilePath(request.getFilePath());
        media.setTakenAt(request.getTakenAt());
        media.setMood(request.getMood());
        albumMediaMapper.update(media);
        return media;
    }

    @Transactional
    public void delete(Long userId, Long id) {
        albumMediaMapper.delete(id, userId);
    }
}
